package com.aijk.commons.jedis;

import com.aijk.commons.cache.RedisConst;
import redis.clients.jedis.JedisCluster;

/**
 * Created by ChenDeWei on 2016/6/30.
 */
public enum RedisUtils {

    INSTANCE;

    RedisUtils() {

    }

    public static boolean lock(JedisCluster jedis, String key, int timeouts) {
        long now = System.currentTimeMillis();
        long result = jedis.setnx(key, String.valueOf(now));
        if (result == RedisConst.OPER_SUCCESS) {
            jedis.expire(key, timeouts);
            return true;
        } else {// 存在锁
            String desc = jedis.get(key);
            if (now - Long.parseLong(desc) > timeouts * 1000) {
                jedis.del(key);// 删除过期锁
                jedis.setnx(key, String.valueOf(now));
            } else {
                return false;
            }
        }
        return true;
    }

    public static void unLock(JedisCluster jedis, String key) {
        jedis.del(key);// 删除过期锁
    }
}
